<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false" :before-close="uploadClose">
      <input
        ref="excel-upload-input"
        hidden
        type="file"
        accept=".xlsx, .xls"
        @change="handleClick"
      >
      <el-button type="warning" icon="el-icon-upload2" @click="importExcel">导入</el-button>
      <div class="downTemplate">
        <span style="margin-right: 10px;">注意：仅可上传固定的Excel模板，如需导入模板，可</span><el-button type="primary" plain icon="el-icon-download" @click="downTemplate()">下载模版</el-button>
      </div>
      <span slot="footer">
        <el-button @click="modelClose">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import excel from 'lay-excel'
import { httpAction } from '@/api/manage'

export default {
  components: {
  },
  props: {
  },
  data() {
    return {
      model: {},
      title: '导入',
      dialogVisible: false,
      dataList: []
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 导入
    importExcel() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      try {
        // 获取导入的文件
        const files = e.target.files
        const rawFile = files[0]
        if (!rawFile) return
        if (this.model.importType === 'GeneralDatabase') {
          // 插件的导入方法
          excel.importExcel(files, {}, (data) => {
            console.log('导入JSON：' + JSON.stringify(data))
            // 列名转英文方法
            const obj = {
              Tablename: 'A'
            }
            const excelColNameArr = ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S']
            for (let i = 1; i <= 18; i++) {
              obj[`Table${i}`] = excelColNameArr[i - 1]
            }
            data = excel.filterImportData(data, obj)
            console.log('梳理后JSON：' + JSON.stringify(data))
            /*  这里要注意 xlsx文件默认的第一页名字叫 sheet1 ,  一般这么写 data[0].sheet1
              如果改过,比如SheetJS ,  这里需要对应修改 data[0].SheetJS
              */
            // 获取表格数据
            this.dataList = data[0].sheet1
            console.log('导入的数据', this.dataList)
            if (this.dataList) {
              this.dataList.shift() // 跳过列头
              if (this.dataList.length > 0) {
                this.importExcelAction()
              }
            } else {
              this.$message.error('导入出错')
            }
            this.$refs['excel-upload-input'].value = ''
          })
        } else if (this.model.importType === 'GetNumberBusiness') {
          // 插件的导入方法
          excel.importExcel(files, {}, (data) => {
            console.log('导入JSON：' + JSON.stringify(data))
            // 列名转英文方法
            const obj = {
              numClass: 'A',
              number: 'B',
              Remarks1: 'C',
              Remarks2: 'D',
              Remarks3: 'E',
              Remarks4: 'F',
              Remarks5: 'G',
              Remarks6: 'H'
            }
            data = excel.filterImportData(data, obj)
            console.log('梳理后JSON：' + JSON.stringify(data))
            /*  这里要注意 xlsx文件默认的第一页名字叫 sheet1 ,  一般这么写 data[0].sheet1
              如果改过,比如SheetJS ,  这里需要对应修改 data[0].SheetJS
              */
            // 获取表格数据
            this.dataList = data[0].sheet1
            console.log('导入的数据', this.dataList)
            if (this.dataList) {
              this.dataList.shift() // 跳过列头
              if (this.dataList.length > 0) {
                this.importExcelAction()
              }
            } else {
              this.$message.error('导入出错')
            }
            this.$refs['excel-upload-input'].value = ''
          })
        }
      } catch (e) {
        this.$message.error('导入错误: ' + e.message)
        this.$refs['excel-upload-input'].value = ''
      }
    },
    // 导入接口
    importExcelAction() {
      const p = {
        dataList: this.dataList
      }
      this.$store.dispatch('app/setLoading', true)
      httpAction(this.model.importUrl, p, 'post').then((res) => {
        if (res.code === 1) {
          this.modelClose()
          this.$message.success(res.message || '操作成功！')
          this.$emit('ok')
        } else {
          this.$message.warning(res.message || '操作失败！')
        }
      }).finally(() => {
        this.$store.dispatch('app/setLoading', false)
      })
    },
    // 显示导入弹窗
    show(model) {
      this.dialogVisible = true
      this.model = model
    },
    // 下载模板
    downTemplate() {
      const fileName = this.model.fileName
      axios({
        method: 'get',
        url: `${process.env.VUE_APP_BASE_API}/file/${fileName}.xlsx`,
        responseType: 'blob'
      }).then(res => {
        const data = res.data
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', fileName + '.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
      }).catch(res => {
        this.$message.error(res.message || '系统异常')
      })
    },
    // 关闭弹窗
    modelClose() {
      this.dialogVisible = false
    },
    // 关闭弹窗
    uploadClose() {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
